package com.smh.yunpicturebackend.config;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyuncs.exceptions.ClientException;
import com.smh.yunpicturebackend.config.property.OSSConfigProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author shiminghui
 * @date 2025/6/17 11:39
 * @description: 对象存储配置类
 */
@Slf4j
@Configuration
@Data
public class OSSClientConfig {

    @Resource
    private OSSConfigProperties ossConfigProperties;

    @Bean
    public OSS ossClient() {
        try {
            // 从系统环境中获取凭证
            EnvironmentVariableCredentialsProvider credentialsProvider =
                    CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);

            return OSSClientBuilder.create()
                    .endpoint(ossConfigProperties.getEndpoint())
                    .credentialsProvider(credentialsProvider)
                    .region(ossConfigProperties.getRegion())
                    .build();
        } catch (ClientException e) {
            log.error("创建OSS客户端失败: " + e.getMessage());
            throw new RuntimeException(e);
        }
    }


}
